import Vue from 'vue'
import VueRouter from 'vue-router'
import Reg from '../views/Reg/Reg.vue'
import Login from '../views/Login/Login.vue'
import Main from '../views/Main/Main.vue'
import store from '../store/index'
import Home from '../views/Menus/Home/Home.vue'
import User from '../views/User/UserInfo.vue'

Vue.use(VueRouter)
// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch((err) => err)
}

const routes = [
  {
    path: '/reg',
    component: Reg
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    component: Main,
    redirect: '/home',
    children: [
      { path: 'home', component: Home },
      { path: 'user-info', component: User }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 前置守卫
router.beforeEach((to, from, next) => {
  if (!store.state.token && to.path !== '/login' && to.path !== '/reg') {
    Vue.prototype.$message.error('请先登录')
    next('/login')
  }
  next()
})

export default router
